package net.hn.hnms.biz.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.biz.project.domain.ProjectInfo;
import net.hn.hnms.biz.project.domain.QualityControlFile;
import net.hn.hnms.biz.project.domain.QualityReport;
import net.hn.hnms.biz.project.enums.QualityFileType;
import net.hn.hnms.biz.project.mapper.ProjectFileMapper;
import net.hn.hnms.biz.project.mapper.ProjectInfoMapper;
import net.hn.hnms.biz.project.mapper.QualityControlFileMapper;
import net.hn.hnms.biz.project.mapper.QualityReportMapper;
import net.hn.hnms.biz.project.request.QualityReportReq;
import net.hn.hnms.biz.project.service.IQualityReportService;
import net.hn.hnms.biz.project.vo.ProjectInfoVo;
import net.hn.hnms.biz.project.vo.QualityReportVo;
import net.hn.hnms.sys.common.core.domain.R;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.utils.tool.Func;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 刘昊
 * @date 2024-03-13 14:10
 */
@Service
@Slf4j
public class QualityReportServiceImpl implements IQualityReportService {
    @Autowired
    private QualityReportMapper qualityReportMapper;

    @Autowired
    private QualityControlFileMapper qualityControlFileMapper;

    @Autowired
    private ProjectInfoMapper projectInfoMapper;



    @Autowired
    private ProjectFileMapper projectFileMapper;

    @Override
    public R<Void> insertReq(QualityReportReq req) {
        QualityReport QualityReport = new QualityReport();
        QualityControlFile QualityControlFile = new QualityControlFile();
        QueryWrapper<ProjectInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id",req.getProjectId());
        //先查询项目信息（项目名称和施工单位）
        ProjectInfo projectInfo = projectInfoMapper.selectById(req.getProjectId());
        if (ObjectUtils.isEmpty(projectInfo)) {
            return R.fail("检查项目信息是否存在");
        }
        try {
            BeanUtils.copyProperties(req,QualityReport);
            BeanUtils.copyProperties(req,QualityControlFile);
            log.info("质量报告新增 ========>");
            QualityReport.setProjectName(projectInfo.getProjectName());
            qualityReportMapper.insert(QualityReport);
            QualityControlFile.setFileType(QualityFileType.TYPE_1.getValue());
            QualityControlFile.setRelevanceId(QualityReport.getQualityReportId());
            log.info("质量报告附件新增 ========>");
            qualityControlFileMapper.insert(QualityControlFile);
        }catch (Exception e) {
            log.error("错误信息:{}",e,e);
            return R.fail("新增失败");
        }
        return R.ok("新增成功");
    }

    @Override
    public R<Void> updateReq(QualityReportReq req) {
        QualityReport QualityReport = new QualityReport();
        QualityControlFile QualityControlFile = new QualityControlFile();
        try {
            BeanUtils.copyProperties(req,QualityReport);
            BeanUtils.copyProperties(req,QualityControlFile);
            log.info("质量报告更新 ========>");
            qualityReportMapper.updateById(QualityReport);
            QualityControlFile.setFileType(QualityFileType.TYPE_3.getValue());
            QualityControlFile.setRelevanceId(QualityReport.getQualityReportId());
            qualityControlFileMapper.insert(QualityControlFile);
        }catch (Exception e) {
            log.info("错误信息:{}",e.getMessage());
            return R.fail("修改检查记录失败");
        }
        return R.ok("修改成功");
    }

    @Override
    public R<Void> deleteList(List<String> idList) {
        try {
            qualityReportMapper.deleteBatchIds(idList);
//            idList.forEach(item -> {
//                qualityReportMapper.deleteById(item);
//            });
        }catch (Exception e) {
            log.info("错误信息:{}",e.getMessage());
            return R.fail("删除失败");
        }
        return R.ok("删除成功");
    }

    @Override
    public R<ResponsePage<List<QualityReportVo>>> selectPageList(QualityReportReq req, PageQuery pageQuery) {
//        QueryWrapper<QualityReport> recordQueryWrapper = new QueryWrapper<>();
        QueryWrapper<QualityControlFile> qualityControlFileQuerywrapper = new QueryWrapper<>();
        List<QualityReportVo> checkRecordVoList = new ArrayList<>();
//        if (StringUtils.isNotBlank(req.getQualityReportId())) {
//            recordQueryWrapper.eq("quality_report_id",req.getQualityReportId());
//        }
//        if (StringUtils.isNotBlank(req.getProjectId())) {
//            recordQueryWrapper.eq("project_id",req.getProjectId());
//        }
//        if (StringUtils.isNotBlank(req.getProjectName())) {
//            recordQueryWrapper.eq("project_name",req.getProjectName());
//        }
//        if (StringUtils.isNotBlank(req.getConstructionUnit())) {
//            recordQueryWrapper.eq("construction_unit",req.getConstructionUnit());
//        }
//        if (StringUtils.isNotBlank(req.getMineCode())) {
//            recordQueryWrapper.eq("mine_code",req.getMineCode());
//        }
//        log.info("质量报告查询 ========>");
//        Page<QualityReport> page = qualityReportMapper.selectPage(pageQuery.build(),recordQueryWrapper);


        //先查询项目信息（项目名称和施工单位）
//        List<ProjectInfoVo> projectListByCondition = projectFileMapper.getProjectListByCondition(req.getProjectId(), req.getConstructionUnit());
        List<ProjectInfoVo> projectListByCondition = projectFileMapper.getProjectListByCondition_new(req.getProjectId(),req.getProjectName(), req.getConstructionUnit());
        if (Func.isNotEmpty(projectListByCondition)) {
            //提取projectId列表
            List<String> projectIds = projectListByCondition.stream()
                    .map(ProjectInfoVo::getProjectId)
                    .collect(Collectors.toList());
            req.setProjectIds(projectIds);

            Page<QualityReport> page = qualityReportMapper.selectPage(pageQuery.build(), buildQuery(req).orderByDesc(QualityReport::getCreateTime));

            List<QualityReportVo> list = page.getRecords().stream().map(o -> {
                QualityReportVo vo = new QualityReportVo();
                BeanUtil.copyProperties(o, vo);

                // 获取项目名称和施工单位信息
                Optional<ProjectInfoVo> projectInfo = projectListByCondition.stream()
                        .filter(p -> p.getProjectId().equals(o.getProjectId()))
                        .findFirst();

                projectInfo.ifPresent(p -> {
                    vo.setProjectName(p.getProjectName());
                    vo.setConstructionUnit(p.getConstructionUnit());
                });

                return vo;
            }).collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(list)) {
                for (QualityReportVo QualityReport : list) {
                    QualityReportVo res = new QualityReportVo();
                    BeanUtils.copyProperties(QualityReport,res);
                    qualityControlFileQuerywrapper.eq("file_type",QualityFileType.TYPE_1.getValue());
                    if(StringUtils.isNotBlank(QualityReport.getQualityReportId())) {
                        qualityControlFileQuerywrapper.eq("relevance_id",QualityReport.getQualityReportId());
                    }
                    List<QualityControlFile> fileDOList = qualityControlFileMapper.selectList(qualityControlFileQuerywrapper);
                    res.setQualityControlFileList(fileDOList);
                    checkRecordVoList.add(res);
                }
            }
            ResponsePage<List<QualityReportVo>> resultPage = new ResponsePage<>(checkRecordVoList,page.getTotal());
            return R.ok("查询完成",resultPage);
        }else{
            ResponsePage<List<QualityReportVo>> resultPage = new ResponsePage<>(checkRecordVoList,0);
            return R.ok("查询完成",resultPage);
        }

    }
    private LambdaQueryWrapper<QualityReport> buildQuery(QualityReportReq req){
        return new LambdaQueryWrapper<QualityReport>()
//                .like(StrUtil.isNotBlank(req.getVehicleCode()), QualityReport::getVehicleCode, req.getVehicleCode())
                .in(!org.springframework.util.CollectionUtils.isEmpty(req.getProjectIds()), QualityReport::getProjectId, req.getProjectIds())
                .eq(StrUtil.isNotBlank(req.getProjectId()), QualityReport::getProjectId, req.getProjectId())
                .eq(StrUtil.isNotBlank(req.getMineCode()), QualityReport::getMineCode, req.getMineCode());
    }
}
